package me.khrystal.store.adapter;

import android.content.Context;
import android.text.format.Formatter;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lzy.okgo.db.DownloadManager;
import com.lzy.okgo.model.Progress;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;

import java.io.File;
import java.text.NumberFormat;
import java.util.List;
import java.util.Map;

import me.khrystal.store.R;
import me.khrystal.store.base.RecyclerAdapter;
import me.khrystal.store.base.RecyclerViewHolder;
import me.khrystal.store.bean.App;
import me.khrystal.store.callback.LogDownloadListener;
import me.khrystal.store.utils.ApkUtils;
import me.khrystal.store.utils.StringUtil;
import me.khrystal.store.widget.NumberProgressBar;

/**
 * usage: 下载管理列表Adapter
 * author: kHRYSTAL
 * create time: 17/7/16
 * update time:
 * email: 723526676@qq.com
 */

public class DownloadAppAdapter extends RecyclerAdapter<DownloadTask> {

    public static final int TYPE_ALL = 0;
    public static final int TYPE_FINISH = 1;
    public static final int TYPE_ING = 2;

    private NumberFormat numberFormat;
    private int type;

    public DownloadAppAdapter(Context context, List<DownloadTask> data, boolean useAnimation) {
        super(context, data, useAnimation);
        numberFormat = NumberFormat.getPercentInstance();
        numberFormat.setMinimumFractionDigits(2);
    }

    public void updateData(int type) {
        // 恢复数据库数据
        this.type = type;
        if (type == TYPE_ALL)
            mData = OkDownload.restore(DownloadManager.getInstance().getAll());
        if (type == TYPE_FINISH)
            mData = OkDownload.restore(DownloadManager.getInstance().getFinished());
        if (type == TYPE_ING)
            mData = OkDownload.restore(DownloadManager.getInstance().getDownloading());
        notifyDataSetChanged();
    }

    @Override
    public int getItemLayoutId(int viewType) {
        return R.layout.item_download;
    }

    /**
     * notice 注意 item参数 始终应为空 真正的App数据应从下载数据库的extra中读取
     */
    @Override
    public void bindData(final RecyclerViewHolder holder, int position, final DownloadTask task) {
        String tag = createTag(task);
        task.register(new ListDownloadListener(tag, holder)).register(new LogDownloadListener());
        holder.itemView.setTag(tag);
        refresh(holder, task.progress);
        App app = (App) task.progress.extra1;
        if (app != null) {
            if (!StringUtil.isNullOrEmpty(app.icon)) {
                Glide.with(mContext).load(app.icon).into(holder.getImageView(R.id.ivIcon));
            } else {
                // TODO: 17/7/16 设置默认icon图片
            }
            if (!StringUtil.isNullOrEmpty(app.name))
                holder.getTextView(R.id.tvName).setText(app.name);
            else
                holder.getTextView(R.id.tvName).setText(task.progress.fileName);

        } else {
            holder.getTextView(R.id.tvName).setText(task.progress.fileName);
            // TODO: 17/7/16 设置默认icon图片
        }

        holder.getButton(R.id.btnStart)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Progress progress = task.progress;
                        switch (progress.status) {
                            case Progress.PAUSE:
                            case Progress.NONE:
                                task.start();
                                break;
                            case Progress.ERROR:
                                task.restart();
                                break;
                            case Progress.LOADING:
                                task.pause();
                                break;
                            case Progress.FINISH:
                                if (ApkUtils.isAvailable(mContext, new File(progress.filePath))) {
                                    ApkUtils.uninstall(mContext, ApkUtils.getPackageName(mContext, progress.filePath));
                                } else {
                                    ApkUtils.install(mContext, new File(progress.filePath));
                                }
                                break;
                        }
                        refresh(holder, progress);
                    }
                });

        holder.getButton(R.id.btnRemove).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                task.remove(true);
                updateData(type);
            }
        });

    }

    private String createTag(DownloadTask task) {
        return type + "_" + task.progress.tag;
    }

    /**
     * 解除注册监听
     */
    public void unRegister() {
        Map<String, DownloadTask> taskMap = OkDownload.getInstance().getTaskMap();
        for (DownloadTask task : taskMap.values()) {
            task.unRegister(createTag(task));
        }
    }

    /**
     * 该方法在下载时频繁调用 用于刷新进度和状态
     */
    private void refresh(RecyclerViewHolder holder, Progress progress) {
        String currentSize = Formatter.formatFileSize(mContext, progress.currentSize);
        String totalSize = Formatter.formatFileSize(mContext, progress.totalSize);
        holder.getTextView(R.id.tvDownloadSize).setText(currentSize + "/" + totalSize);
        TextView tvNetSpeed = holder.getTextView(R.id.tvNetSpeed);
        Button btnStart = holder.getButton(R.id.btnStart);
        switch (progress.status) {
            case Progress.NONE:
                tvNetSpeed.setText("停止");
                btnStart.setText("下载");
                break;
            case Progress.PAUSE:
                tvNetSpeed.setText("暂停中");
                btnStart.setText("继续");
                break;
            case Progress.ERROR:
                tvNetSpeed.setText("下载出错");
                btnStart.setText("重新下载");
                break;
            case Progress.WAITING:
                tvNetSpeed.setText("等待中");
                btnStart.setText("等待");
                break;
            case Progress.FINISH:
                tvNetSpeed.setText("下载完成");
                btnStart.setText("打开");
                break;
            case Progress.LOADING:
                String speed = Formatter.formatFileSize(mContext, progress.speed);
                tvNetSpeed.setText(String.format("%s/s", speed));
                btnStart.setText("暂停");
                break;
        }
        holder.getTextView(R.id.tvProgress).setText(numberFormat.format(progress.fraction));
        NumberProgressBar progressBar = (NumberProgressBar) holder.getView(R.id.pbProgress);
        progressBar.setMax(10000);
        progressBar.setProgress((int) (progress.fraction * 10000));
    }

    private class ListDownloadListener extends DownloadListener {

        private RecyclerViewHolder holder;

        public ListDownloadListener(Object tag, RecyclerViewHolder holder) {
            super(tag);
            this.holder = holder;
        }

        @Override
        public void onStart(Progress progress) {
            // do nothing
        }

        @Override
        public void onProgress(Progress progress) {
            if (tag == holder.itemView.getTag())
                refresh(holder, progress);
        }

        @Override
        public void onError(Progress progress) {
            Throwable throwable = progress.exception;
            if (throwable != null)
                throwable.printStackTrace();
        }

        @Override
        public void onFinish(File file, Progress progress) {
            Toast.makeText(mContext, "下载完成:" + progress.filePath, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onRemove(Progress progress) {

        }
    }
}
